package com.android.scanner;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.scanner.bean.UserBean;
import com.android.scanner.fragment.BBDelayFragment;
import com.android.scanner.fragment.BBGetPwdFragment;
import com.android.scanner.fragment.BBListDeleteFragment;
import com.android.scanner.fragment.BBListFragment;
import com.android.scanner.fragment.BBOptionFragment;
import com.android.scanner.fragment.BBScanFragment;
import com.android.scanner.fragment.BBSingleTestFragment;
import com.android.scanner.fragment.BaseFragment;
import com.android.scanner.fragment.CenterFragment;
import com.android.scanner.fragment.DeleteFragment;
import com.android.scanner.fragment.DeviceFragment;
import com.android.scanner.fragment.DisplayFragment;
import com.android.scanner.fragment.GetPassFragment;
import com.android.scanner.fragment.LinkFragment;
import com.android.scanner.fragment.LoginFragment;
import com.android.scanner.fragment.NewWorkFragment;
import com.android.scanner.fragment.OptionFragment;
import com.android.scanner.fragment.OrderFragment;
import com.android.scanner.fragment.PassInfoFragment;
import com.android.scanner.fragment.SendDataFragment;
import com.android.scanner.fragment.SettingsFragment;
import com.android.scanner.fragment.TimeFragment;
import com.android.scanner.utils.Constant;
import com.android.scanner.utils.SysUtil;
import com.android.scanner.utils.StatusUtil;

public class MainActivity extends FragmentActivity {

	private TextView tvTime;
	private ImageView ivBa;
	private ImageView ivSignal;
	private ImageView ivWifi;
	private int timer = 60 * 1000;
	private TelephonyManager Tel;
	private MyPhoneStateListener MyListener;
	private BaseFragment curFragment = null;
	private boolean isHoldKey = true;
	private BatteryReceiver batteryReceiver;
	private WifiReceiver wifiReceiver;

	// private CenterFragment center = null;
	// private OptionFragment option = null;
	// private DeleteFragment dfrag = null;
	// private SettingsFragment settings = null;
	// private OrderFragment order = null;
	// private DisplayFragment display = null;
	// private TimeFragment tfrag = null;
	// private BBListFragment bbfrg = null;

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Log.e("kirk", "kirk add - msgwhat is " + msg.what);
			if (msg.what == Constant.MSG_SETTING_DISPLAY
					|| msg.what == Constant.MSG_SETTING_TIME) {
				isHoldKey = true;
			} else {
				isHoldKey = false;
			}

			switch (msg.what) {
			case Constant.MSG_MAIN_OPTION:
			case Constant.MSG_BACK_OPTION:
				// showOptionFragment();
				replaceFragment(OptionFragment.getInstance(handler, msg.what));
				break;

			case Constant.MSG_MAIN_PAGE:
				// showMainFragment();
				replaceFragment(CenterFragment.getInstance(handler));
				break;

			case Constant.MSG_MAIN_NEWWORK:
				// showMainFragment();
				replaceFragment(NewWorkFragment.getInstance(handler));
				break;

			case Constant.MSG_MAIN_LOGIN:
				// showMainFragment();
				replaceFragment(LoginFragment.getInstance(handler));
				break;

			case Constant.MSG_OPTION_DELETE:
				// showDeleteFragment();
				replaceFragment(DeleteFragment.getInstance(handler));
				break;

			case Constant.MSG_OPTION_SETTINGS:
			case Constant.MSG_BACK_SETTINGS:
				// showSettingsFragment();
				replaceFragment(SettingsFragment.getInstance(handler, msg.what));
				break;

			case Constant.MSG_OPTION_ORDER:
				// showOrderFragment();
				replaceFragment(OrderFragment.getInstance(handler));
				break;

			case Constant.MSG_OPTION_GETPASS:
				// showOrderFragment();
				replaceFragment(GetPassFragment.getInstance(handler, msg.arg1));
				break;

			case Constant.MSG_OPTION_PASSINFO:
				replaceFragment(PassInfoFragment.getInstance(handler));
				break;

			case Constant.MSG_OPTION_SENDDATA:
				// showOrderFragment();
				replaceFragment(SendDataFragment.getInstance(handler, msg.arg1));
				break;

			case Constant.MSG_SETTING_LINK:
				// showDisplayFragment();
				replaceFragment(LinkFragment.getInstance(handler));
				break;

			case Constant.MSG_SETTING_DISPLAY:
				// showDisplayFragment();
				replaceFragment(DisplayFragment.getInstance(handler));
				break;

			case Constant.MSG_SETTING_TIME:
				// showTimeFragment();
				replaceFragment(TimeFragment.getInstance(handler));
				break;

			case Constant.MSG_SETTING_DEVICE:
				// showTimeFragment();
				replaceFragment(DeviceFragment.getInstance(handler));
				break;

			case Constant.BB_TEST:
				switch (msg.arg1) {
				case 0:
					replaceFragment(BBListFragment.getInstance(handler));
					break;
				case 1:
					replaceFragment(BBOptionFragment.getInstance(handler));
					break;
				}
				break;
			case Constant.BB_OPTION:
				replaceFragment(BBOptionFragment.getInstance(handler));
				break;

			case Constant.BB_LIST:
				replaceFragment(BBListFragment.getInstance(handler));
				break;
			case Constant.BB_SET_DELAY:
				replaceFragment(BBDelayFragment.getInstance(handler));
				break;
			case Constant.BB_GET_PWD:
				replaceFragment(BBGetPwdFragment.getInstance(handler));
				break;
			case Constant.BB_SCAN:
				replaceFragment(BBScanFragment.getInstance(handler));
				break;
			case Constant.BB_SINGLE_TEST:
				replaceFragment(BBSingleTestFragment.getInstance(handler,
						msg.arg1));
				break;
			case Constant.BB_DELETE:
				replaceFragment(BBListDeleteFragment.getInstance(handler));
				break;

			// api
			case Constant.MSG_USER_LOGIN:
				UserBean user = (UserBean) msg.obj;
				if (user == null) {
					Toast.makeText(getApplicationContext(), "user error",
							Toast.LENGTH_SHORT).show();
				} else {
					handler.sendEmptyMessage(Constant.MSG_MAIN_PAGE);
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initViews();
		initTime();

		replaceFragment(LoginFragment.getInstance(handler));

		initReceiver();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Tel.listen(MyListener, PhoneStateListener.LISTEN_NONE);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		try {
			unregisterReceiver(batteryReceiver);
			unregisterReceiver(wifiReceiver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private void initReceiver() {
		// TODO Auto-generated method stub
		// BatteryReceiver
		IntentFilter intentFilter = new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED);
		batteryReceiver = new BatteryReceiver();
		registerReceiver(batteryReceiver, intentFilter);

		IntentFilter wifiIntentFilter = new IntentFilter(
				WifiManager.WIFI_STATE_CHANGED_ACTION);
		wifiReceiver = new WifiReceiver();
		registerReceiver(wifiReceiver, wifiIntentFilter);

		// PhoneStateListener
		MyListener = new MyPhoneStateListener();
		Tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		Tel.listen(MyListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

	}

	private void initTime() {
		// TODO Auto-generated method stub
		Runnable runable = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				getCurrentTime();
				handler.postDelayed(this, timer);
			}
		};

		handler.postDelayed(runable, timer);
	}

	private void initViews() {
		// TODO Auto-generated method stub
		tvTime = (TextView) findViewById(R.id.tv_time);
		ivBa = (ImageView) findViewById(R.id.iv_ba);
		ivSignal = (ImageView) findViewById(R.id.iv_signal);
		ivWifi = (ImageView) findViewById(R.id.iv_wifi);
		getCurrentTime();
	}

	//
	// private void showMainFragment() {
	// // TODO Auto-generated method stub
	// FragmentTransaction t = this.getSupportFragmentManager()
	// .beginTransaction();
	// if (center == null)
	// center = new CenterFragment(handler);
	// t.replace(R.id.center_frame, center);
	// t.commit();
	//
	// curFragment = center;
	// }
	//
	// private void showOptionFragment() {
	// // TODO Auto-generated method stub
	// FragmentTransaction t = this.getSupportFragmentManager()
	// .beginTransaction();
	// if (option == null)
	// option = new OptionFragment(handler);
	// t.replace(R.id.center_frame, option);
	// t.commit();
	//
	// curFragment = option;
	// }
	//
	// private void showDeleteFragment() {
	// // TODO Auto-generated method stub
	// FragmentTransaction t = this.getSupportFragmentManager()
	// .beginTransaction();
	// if (dfrag == null)
	// dfrag = new DeleteFragment(handler);
	// t.replace(R.id.center_frame, dfrag);
	// t.commit();
	//
	// curFragment = dfrag;
	// }
	//
	// private void showSettingsFragment() {
	// // TODO Auto-generated method stub
	// FragmentTransaction t = this.getSupportFragmentManager()
	// .beginTransaction();
	// if (settings == null)
	// settings = new SettingsFragment(handler);
	// t.replace(R.id.center_frame, settings);
	// t.commit();
	//
	// curFragment = settings;
	// }
	//
	// private void showOrderFragment() {
	// // TODO Auto-generated method stub
	// FragmentTransaction t = this.getSupportFragmentManager()
	// .beginTransaction();
	// if (order == null)
	// order = new OrderFragment(handler);
	// t.replace(R.id.center_frame, order);
	// t.commit();
	//
	// curFragment = order;
	// }
	//
	// private void showDisplayFragment() {
	// // TODO Auto-generated method stub
	// FragmentTransaction t = this.getSupportFragmentManager()
	// .beginTransaction();
	// if (display == null)
	// display = new DisplayFragment(handler);
	// t.replace(R.id.center_frame, display);
	// t.commit();
	//
	// curFragment = display;
	// }
	//
	// private void showTimeFragment() {
	// // TODO Auto-generated method stub
	// FragmentTransaction t = this.getSupportFragmentManager()
	// .beginTransaction();
	// if (tfrag == null)
	// tfrag = new TimeFragment(handler);
	// t.replace(R.id.center_frame, tfrag);
	// t.commit();
	//
	// curFragment = tfrag;
	// }

	private void replaceFragment(BaseFragment fragment) {
		FragmentTransaction t = this.getSupportFragmentManager()
				.beginTransaction();
		t.replace(R.id.center_frame, fragment);
		t.commit();

		curFragment = fragment;
	}

	private void getCurrentTime() {
		String str = SysUtil.getCurrentTime("yyyy-MM-dd HH:mm");
		tvTime.setText(str);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		int keyCode = event.getKeyCode();
		Log.e("kirk", "kirk add - dispatchKeyEvent keyCode is " + keyCode);
		// if (curFragment == DisplayFragment.getInstance(handler)
		// || curFragment == TimeFragment.getInstance(handler)) {
		// if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
		// || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
		// || keyCode == KeyEvent.KEYCODE_DPAD_UP
		// || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
		// return super.dispatchKeyEvent(event);
		// }
		// }
		// if (event.getRepeatCount() == 1
		// && event.getAction() == KeyEvent.ACTION_DOWN) {
		// return curFragment.setKeyEvent(keyCode, event);
		// }

		return super.dispatchKeyEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		Log.e("kirk", "kirk add - onKeyDown keyCode is " + keyCode);
		if (isHoldKey) {
			if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT
					|| keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
					|| keyCode == KeyEvent.KEYCODE_DPAD_UP
					|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
				return super.onKeyDown(keyCode, event);
			}
		}

		return curFragment.setKeyEvent(keyCode, event);
		// return super.onKeyDown(keyCode, event);
	}

	private class BatteryReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			// �ж����Ƿ���Ϊ�����仯��Broadcast Action
			if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
				// ��ȡ��ǰ����
				int level = intent.getIntExtra("level", 0);
				// �������̶ܿ�
				int scale = intent.getIntExtra("scale", 100);
				// ����ת�ɰٷֱ�

				ivBa.setBackgroundResource(StatusUtil
						.getBatteryStatus((level * 100) / scale));
			}
		}

	}

	private class MyPhoneStateListener extends PhoneStateListener {

		@Override
		public void onSignalStrengthsChanged(SignalStrength signalStrength) {

			super.onSignalStrengthsChanged(signalStrength);

			ivSignal.setBackgroundResource(StatusUtil
					.getGSMStatus(signalStrength.getGsmSignalStrength()));
		}

	};

	private class WifiReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			int wifi_state = intent.getIntExtra("wifi_state", 0);
			int mRssi = Math.abs(((WifiManager) getSystemService(WIFI_SERVICE))
					.getConnectionInfo().getRssi());
			int level = WifiManager.calculateSignalLevel(mRssi, 4);

			switch (wifi_state) {
			case WifiManager.WIFI_STATE_DISABLING:
				ivWifi.setImageResource(R.drawable.wifi_signal);
				ivWifi.setImageLevel(level);
				ivWifi.setVisibility(View.GONE);
				break;
			case WifiManager.WIFI_STATE_DISABLED:
				ivWifi.setImageResource(R.drawable.wifi_signal);
				ivWifi.setImageLevel(level);
				ivWifi.setVisibility(View.GONE);
				break;
			case WifiManager.WIFI_STATE_ENABLING:
				ivWifi.setImageResource(R.drawable.wifi_signal);
				ivWifi.setImageLevel(level);
				ivWifi.setVisibility(View.VISIBLE);
				break;
			case WifiManager.WIFI_STATE_ENABLED:
				ivWifi.setImageResource(R.drawable.wifi_signal);
				ivWifi.setImageLevel(level);
				ivWifi.setVisibility(View.VISIBLE);
				break;
			case WifiManager.WIFI_STATE_UNKNOWN:
				ivWifi.setImageResource(R.drawable.wifi_signal);
				ivWifi.setImageLevel(level);
				ivWifi.setVisibility(View.GONE);
				break;
			}
		}

	}

}
